package Day2025_03_28;

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public class Demo05 {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        int n1 = 0, n2 = 0;
        ListNode cur1 = pHead1;
        ListNode cur2 = pHead2;
        while (cur1 != null) {
            cur1 = cur1.next;
            n1++;
        }
        while (cur2 != null) {
            cur2 = cur2.next;
            n2++;
        }
        int n = n1 - n2;
        if (n < 0) {
            n = -n;
            while (n-- != 0) pHead2 = pHead2.next;
        } else {
            while (n-- != 0) pHead1 = pHead1.next;
        }
        while (pHead1 != pHead2) {
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }
        return pHead1;
    }

    public static void main(String[] args) {
        Demo05 demo05 = new Demo05();
        ListNode pHead1 = new ListNode(1);
        pHead1.next = new ListNode(2);
        pHead1.next.next = new ListNode(3);
        pHead1.next.next.next = new ListNode(4);
        pHead1.next.next.next.next = new ListNode(5);
        pHead1.next.next.next.next.next = new ListNode(6);
        ListNode pHead2 = new ListNode(10);
        pHead2.next = new ListNode(9);
        pHead2.next.next = pHead1.next.next.next;
        ListNode ret = demo05.FindFirstCommonNode(pHead1, pHead2);
        System.out.println(ret.val);
    }
}
